<template>
  <scroll-view
    scroll-y="true"
    :scroll-top="scrollTop"
    class="message-scroll-list"
    @scroll="scroll"
    :refresher-triggered="triggered"
    :refresher-enabled="true"
    @refresherrefresh="onLoadMore"
  >
    <div @touchstart="handleTapMessageList" id="msg-list" class="msg-list" ref="msgList">
      <div v-show="!noMore" @click="onLoadMore" class="view-more-text">下拉加载更多</div>
      <view class="msg-tip" v-show="noMore">{{ t('noMoreText') }}</view>
      <div v-for="(item, index) in finalMsgs" :key="item.messageClientId">
        <MessageItem
          :msg="item"
          :key="item.messageClientId"
          :reply-msg="replyMsgsMap && replyMsgsMap[item.ReplyMessageClientId]"
        ></MessageItem>
      </div>
      <!-- <div v-if="isIosH5" class="block"></div> -->
    </div>
  </scroll-view>
</template>

<script lang="ts" setup>
import {
  ref,
  computed,
  getCurrentInstance,
  onBeforeMount,
  onUnmounted,
  nextTick,
  watch
} from '../../../utils/transformVue'
import MessageItem from './message-item.vue'
import { events, MSG_ID_FLAG } from '../../../utils/constants'
import { caculateTimeago } from '../../../utils/date'
import { onPageScroll } from '@dcloudio/uni-app'
import { getUniPlatform } from '../../../utils'
import { t } from '../../../utils/i18n'
const props = defineProps({
  msgs: {
    type: Array,
    required: true
  },
  noMore: {
    type: Boolean,
    default: undefined
  },
  replyMsgsMap: {
    type: Object,
    default: undefined
  },
  direction: {
    default: 0
  }
})

const isKeyboardUp = ref(false)
const uniPlatform = getUniPlatform()
// const isIosH5 = uniPlatform == 'web' && uni.getSystemInfoSync().platform == 'ios'
const scrollTop = ref(9999)
const old = ref({
  scrollTop: 0
})
const finalMsgs = ref([])

const scroll = (e) => {
  old.value.scrollTop = e.detail.scrollTop
}

watch(
  () => props.msgs,
  (val, o) => {
    const res = []
    //   console.log(props.msgs, '----------------')
    props.msgs.forEach((item, index) => {
      // 如果两条消息间隔超过5分钟，插入一条自定义时间消息
      // @ts-ignore
      if (index > 0 && item.createTime - props.msgs[index - 1].createTime > 5 * 60 * 1000) {
        // @ts-ignore
        res.push({
          messageClientId: 'time-' + item.createTime,
          messageType: 100,
          attachment: {
            type: 'time',
            value: caculateTimeago(item.createTime)
          },
          sendingState: 1,
          createTime: item.createTime
        })
      }
      res.push(item)
    })

    console.log('finalMsgs: -----------', res)

    finalMsgs.value = res

    if (props.direction) {
      nextTick(() => {
        setTimeout(() => {
          scrollToTop()
        }, 0)
      })
    } else {
      nextTick(() => {
        setTimeout(() => {
          scrollToBottom()
        }, 0)
      })
    }
  },
  {
    deep: true
  }
)

// const start = ref(0)
// const end = computed(() => start.value + HISTORY_LIMIT)

// let lock = false

onPageScroll(() => {
  isKeyboardUp.value = false
})

const scrollToTop = () => {
  scrollTop.value = old.value.scrollTop
  nextTick(() => {
    scrollTop.value = 0
  })
}

// 消息滑动到底部，建议搭配 nextTick 使用
const scrollToBottom = () => {
  scrollTop.value = old.value.scrollTop
  nextTick(() => {
    scrollTop.value = 10000
  })
}

const triggered = ref(false)

const onLoadMore = () => {
  if (triggered.value) {
    return
  }
  if (!props.noMore) {
    uni.$emit(events.GET_HISTORY_MSG, finalMsgs.value[0])
  }
  triggered.value = true
  setTimeout(() => {
    triggered.value = false
  }, 500)
}

const handleTapMessageList = () => {
  // 处理滚动穿透
  uni.$emit(events.CLOSE_EMOJI, false)
  uni.hideKeyboard()
}

onBeforeMount(() => {
  uni.$on(events.SEND_MSG, () => {
    scrollToBottom()
  })

  uni.$on(events.ON_CHAT_MOUNTED, (msg) => {
    if (uniPlatform === 'mp-weixin') {
      scrollToBottom()
    } else {
      setTimeout(() => {
        scrollToBottom()
      }, 100)
    }
  })

  uni.$on(events.ON_MSG, () => {
    setTimeout(() => {
      scrollToBottom()
    }, 300)
  })

  uni.$on(events.ON_SCROLL_BOTTOM, () => {
    setTimeout(() => {
      scrollToBottom()
    }, 0)
  })

  uni.$on(events.ON_LOAD_MORE, () => {
    const msg = finalMsgs.value.filter(
      (item) =>
        !(item.type === 'custom' && ['beReCallMsg', 'reCallMsg'].includes(item.attach?.type || ''))
    )[0]
    if (msg) {
      uni.$emit(events.GET_HISTORY_MSG, msg)
    }
  })

  uni.$on(events.ON_INPUT_FOCUS_CHANGE, (flag) => {
    isKeyboardUp.value = flag
  })

  // uni.$on(events.ON_REACH_BOTTOM, () => {
  // if (end.value < props.msgs.length && !lock) {
  //   lock = true
  //   start.value += HISTORY_LIMIT
  //   setTimeout(() => {
  //     lock = false
  //   }, 1500)
  // }
  // console.log('到底了！！！！', 'start: ', start.value, 'lock: ', lock, 'msg.lenght: ', props.msgs.length)
  // })
})

// uni.$on(events.ON_REACH_TOP, () => {
//   if (start.value > 0 && !lock) {
//     lock = true
//     start.value -= HISTORY_LIMIT
//     setTimeout(() => {
//       lock = false
//     }, 1500)
//   }
//   console.log('到顶了！！！！', 'start: ', start.value, 'lock: ', lock, 'msg.lenght: ', props.msgs.length)
// })

onUnmounted(() => {
  uni.$off(events.SEND_MSG)

  uni.$off(events.ON_CHAT_MOUNTED)

  uni.$off(events.ON_MSG)

  uni.$off(events.ON_SCROLL_BOTTOM)

  uni.$off(events.ON_LOAD_MORE)

  uni.$off(events.ON_INPUT_FOCUS_CHANGE)
})
</script>

<style scoped lang="scss">
.msg-list {
  padding: 0 16px 120px;
  box-sizing: border-box;
  transition: all 0.3s cubic-bezier(0.645, 0.045, 0.355, 1);
  overflow-x: hidden;
}

.msg-tip {
  text-align: center;
  color: #b3b7bc;
  font-size: 12px;
  margin-top: 10px;
}

.block {
  width: 100%;
  height: 40px;
}

.message-scroll-list {
  height: 90vh;
  box-sizing: border-box;
  padding-bottom: 1px;
}

.view-more-text {
  text-align: center;
  color: #b3b7bc;
  font-size: 15px;
  margin-top: 20px;
}
</style>
